<?php

namespace app\admin\model\yunfood;

/**
 * 订单 - 发票申请
 */
class OrderInvoice extends \addons\yunfood\model\OrderInvoice
{
    // 自定义初始化
    protected static function init()
    {
        self::beforeWrite(function ($record) {
            $scenario = $record->data['scenario'] ?? null;
            if ($scenario === 'reply') {
                if ($record->status == self::STATUS_WAIT) {
                    $record->invoice_time = time();
                    $agree = $record['agree'];
                    $record->status = $agree ? self::STATUS_DONE : self::STATUS_REFUSE;
                    if ($orderData = $record->orderData) {
                        $orderData->invoice_status = $agree ? Order::INVOICE_STATUS_DOWN : Order::INVOICE_STATUS_REFUSE;
                        $orderData->save();
                    }
                }
            }

            if (! empty($record->data['deleted_at'])) {
                if ($orderData = $record->orderData) {
                    if ($orderData->invoice_no == $record->invoice_no) {
                        $orderData->invoice_no = null;
                        $orderData->invoice_status = Order::INVOICE_STATUS_NO;
                        $orderData->save();
                    }
                }
            }
        });
    }
}
